import pymysql
from log import *

日志 = 日志类(2)

# 数据库连接配置
# host = 'localhost'
# user = 'root'
# password = 'root'
# database = 'license'

host = '43.143.110.221'
user = 'root'
password = 'aa125879'
database = 'license'

class DB:
    def __init__(self):
        self.host = host
        self.user = user
        self.password = password
        self.database = database


    def open(self):
        try:
            with pymysql.connect(
                    host=self.host,
                    user=self.user,
                    password=self.password,
                    database=self.database,
                    cursorclass=pymysql.cursors.DictCursor
            ) as conn:
                print("mySql连接成功！")
        except pymysql.Error as e:
            print(f"连接失败: {e}")
            exit(1)
        cursor = conn.cursor()

        return cursor,conn

    def close(self, cursor, conn):
        cursor.close()
        conn.close()

    def execute_select(self, sql, args=None):
        cursor,conn = self.open()
        conn.ping(reconnect=True)
        try:
            cursor.execute(sql,args)
            conn.commit()
            result = cursor.fetchall()
        except pymysql.Error as e:
            print(f"查询失败: {e}")
            日志.显示内容到界面("execute_select", f"查询失败: {e}")
            raise ValueError(f"查询失败: {e}")
        self.close(cursor,conn)
        return result

    def execute_insert(self, sql, args):
        cursor,conn = self.open()
        conn.ping(reconnect=True)
        try:
            cursor.execute(sql, args)
            conn.commit()
        except pymysql.Error as e:
            print(f"新增失败: {e}")
            日志.显示内容到界面("execute_insert", f"新增失败: {e}")
            conn.rollback()
            raise ValueError(f"新增失败: {e}")
        self.close(cursor,conn)

    def execute_update(self, sql, args):
        cursor,conn = self.open()
        conn.ping(reconnect=True)
        try:
            cursor.execute(sql, args)
            conn.commit()
        except pymysql.Error as e:
            print(f"修改失败: {e}")
            日志.显示内容到界面("execute_update", f"修改失败: {e}")
            conn.rollback()
            raise ValueError(f"修改失败: {e}")
        self.close(cursor,conn)